package com.ryf.maven.servlet.student;

import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;
import com.ryf.maven.dao.StudentDao;
import com.ryf.maven.entity.BaseResponse;
import com.ryf.maven.entity.Student;
import com.ryf.maven.utils.RequestUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description
 * @ClassName StudentUpdateServlet
 * @Author L-Cohen
 * @date 2020.12.03 12:56
 */
@WebServlet(urlPatterns = "/update/stu")
public class StudentUpdateServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        Gson gson = new Gson();
        String stuJson = RequestUtil.getRequestBody(req);
        // 修改时提交的数据
        Student stuBody = gson.fromJson(stuJson, Student.class);

        // 数据本地数据
        Student student = StudentDao.getStuByStuNo(stuBody.getStuNo());
        if (!StringUtils.isNullOrEmpty(stuBody.getStuName()))
        {
            student.setStuName(stuBody.getStuName());
            student.setSex(stuBody.getSex());
            student.setBirth(stuBody.getBirth());
            student.setNat(stuBody.getNat());
            student.setS_class(stuBody.getS_class());
        }

        int rows = StudentDao.updateStu(student);
        BaseResponse<Integer> baseResponse = new BaseResponse<Integer>();
        if (rows > 0)
        {
            baseResponse.setCode(200);
            baseResponse.setMsg("更新成功");
        }
        else
        {
            baseResponse.setCode(600);
            baseResponse.setMsg("更新失败");
        }
        baseResponse.setData(rows);


        String json = gson.toJson(baseResponse);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
    }
}
